package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/12 9:13
 */
public class DwmUvApp extends BaseAppV1 {
    public static void main(String[] args) {
        new DwmUvApp().init(3001, 1, "DwmUvApp", "DwmUvApp", Constant.TOPIC_DWD_PAGE);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
//        stream.print("pre: ");
        /*
        {
          "common": {
            "ar": "370000",
            "uid": "40",
            "os": "Android 11.0",
            "ch": "oppo",
            "is_new": 0,
            "md": "Xiaomi 10 Pro ",
            "mid": "mid_47",
            "vc": "v2.1.134",
            "ba": "Xiaomi"
          },
          "page": {
            "page_id": "payment",
            "item": "2,9",
            "during_time": 9760,
            "item_type": "sku_ids",
            "last_page_id": "trade"
          },
          "ts": 1644629262000
        }
         */
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
            
                private SimpleDateFormat sdf;
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> firstWindowState;
            
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstWindowState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("firstWindowState", Boolean.class));
                    yesterdayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
                
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                
                }
            
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 考虑到了第二天
                    String yesterday = yesterdayState.value();
                    String today = sdf.format(ctx.window().getStart());
                    if (!today.equals(yesterday)) {
                        firstWindowState.clear();
                    
                        // 把today存入到状态中
                        yesterdayState.update(today);
                    
                    }
                
                    if (firstWindowState.value() == null) {
                        firstWindowState.update(true);
                    
                        // 当天第一个窗口, 找到时间戳最小的那条数据
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        out.collect(min);
                    }
                
                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWM_UV));
        
    }
}
/*
dmw层uv的干什么事情?
 去重, 把去重后的详情写入到dwm层(kafka中)
 
 来源日志数据
 
 dwd_page dwd_start dwd_display
 
 dwd_start
    只保留这个设备的第一条启动记录
    
    将来结果可能会偏小!
    
    如果是通过浏览器访问, 则没有启动日志
    只有通过app访问, 才能拿到启动日志
    
 dwd_page
    只需要记录用户当天第一条访问记录
    

 */